package com.ali.gts.servlet.service.impl;

import com.ali.gts.servlet.dao.BookDao;
import com.ali.gts.servlet.dao.OrderDao;
import com.ali.gts.servlet.dao.OrderItemDao;
import com.ali.gts.servlet.dao.impl.BookDaoImpl;
import com.ali.gts.servlet.dao.impl.OrderDaoImpl;
import com.ali.gts.servlet.dao.impl.OrderItemDaoImpl;
import com.ali.gts.servlet.domain.*;
import com.ali.gts.servlet.service.OrderService;

import java.util.Date;
import java.util.HashMap;

public class OrderServiceImpl implements OrderService {
    OrderItemDao orderItemDao = new OrderItemDaoImpl();
    OrderDao orderDao = new OrderDaoImpl();
    BookDao bookDao = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, String userId) {
        String orderId = System.currentTimeMillis()+""+userId;
        Order order = new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
        orderDao.saveOrder(order);

        HashMap<Integer, CartItem> items = cart.getItems();

        items.forEach((num,cartItem)->{
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getItemCount(),cartItem.getPrice(),cartItem.getItemTotalPrice(),orderId);
            orderItemDao.saveOrderItem(orderItem);
            //查询商品
            Book book = bookDao.queryBookById(cartItem.getId());
            //修改数的销量
            book.setSales(book.getSales() + cartItem.getItemCount());

            //修改库存
            book.setStock(book.getStock() - cartItem.getItemCount());


            bookDao.updateBook(book);

        });

        //购物车清空
        cart.clearItem();

        return orderId;
    }
}
